package com.qian.service.ddj.serviceImpl;

import com.qian.api.ddj.model.Holiday;
import com.qian.api.ddj.service.IHolidayService;
import com.qian.service.ddj.dao.HolidayRepository;
import com.qian.service.ddj.entity.DdjHoliday;
import com.yaowk.service.common.BaseRepository;
import com.yaowk.service.common.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class HolidayServiceImpl extends BaseServiceImpl<Holiday, DdjHoliday, Integer> implements IHolidayService {

    @Autowired
    private HolidayRepository dao;

    @Override
    public boolean verifyHoliday(Date date) {
        List<DdjHoliday> all = dao.findAll();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        long time = calendar.getTimeInMillis();
        for (DdjHoliday holiday : all) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(holiday.getDate());
            if (calendar.getTimeInMillis() == time) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Holiday saveOrUpdate(Holiday holiday) {
        DdjHoliday ddjHoliday = new DdjHoliday();
        if (holiday.isNew()) {
            dao.save(model2Entity(holiday));
        } else {
            ddjHoliday = dao.findOne(holiday.getId());
            if (isNotEmpty(holiday.getDate())) {
                ddjHoliday.setDate(holiday.getDate());

            }
            holiday = entity2model(dao.save(ddjHoliday));
        }
        return holiday;
    }

    @Override
    protected BaseRepository getDao() {
        return dao;
    }

    @Override
    protected DdjHoliday model2Entity(Holiday model) {
        DdjHoliday ddjHoliday = null;
        if (isNotEmpty(model)) {
            ddjHoliday = new DdjHoliday();
            ddjHoliday.setDate(model.getDate());
            ddjHoliday.setId(model.getId());
        }
        return ddjHoliday;
    }

    @Override
    protected Holiday entity2model(DdjHoliday entity) {
        Holiday holiday = null;
        if (isNotEmpty(entity)) {
            holiday = new Holiday();
            holiday.setDate(entity.getDate());
            holiday.setId(entity.getId());
        }
        return holiday;
    }
}
